package com.taihe.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.taihe.constants.WeiXinConstants;
import com.taihe.domain.TsPlatformUser;
import com.taihe.service.TsPlatformUserService;
import com.taihe.util.wechat.CommonUtils;
import com.taihe.util.wechat.WeiXinUser;
import com.taihe.util.wechat.WeixinOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;

/**
 * Created by zwt on 2018/7/24.
 */
@Controller
@RequestMapping("index")
public class IndexController {

    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private TsPlatformUserService tsPlatformUserService;

    /**
     *
     * @param request
     * @param response
     * @param htmlFlag  0 推影入驻页面  1 我的奖励 2 有奖邀请
     * @param model
     * @return
     */
    @RequestMapping("sub")
    public String index(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam(required = true) Integer htmlFlag, Model model){
        WeixinOAuth2AccessToken weixinOAuth2AccessToken = null; //网页授权接口调用凭证token
        WeiXinUser weiXinUser = null; //微信用户信息
        TsPlatformUser tsPlatformUser = null; //平台用户信息
        String openId= "od3gx0XY8F6O_-dL-DJttO1w9IAE";
        String code = request.getParameter("code");
        TsPlatformUser user = null;
        JSONObject result = new JSONObject();
        logger.error("用户进来的code====="+code);
        logger.error("用户进来的openId====="+openId);
        if ("authdeny".equals(code)){
            result.put("errorMsg", "系统繁忙");
            result.put("status", 400);
            this.print(response, result.toJSONString());
            return null;
        }
        //code第一次请求会是空 请求微信链接获取获取授权token的code
        /*if (StringUtils.isBlank(code)){
            return "redirect:"+ CommonUtils.generateUrl(request);
        }*/
        logger.error("如果用户进来后获取的code为null，授权后获取的code===="+code);

        /**
         * //根据code换取网页授权token 并根据网页授权token和openId获取用户信息
         *  将网页授权信息放到session中 避免再次请求的时候使用同一个code导致报错
          */
        if (StringUtils.isNotBlank(code) && StringUtils.isBlank(openId)) {
            weixinOAuth2AccessToken = CommonUtils.getWeixinOAuth2AccessToken(WeiXinConstants.APPID, WeiXinConstants.APPSECRET, code);
            logger.error("=因为code一致导致weixinOAuth2AccessToken.getOpenId()====="+weixinOAuth2AccessToken.getOpenId());
            logger.error("根据code换取的weixinOAuth2AccessToken"+weixinOAuth2AccessToken.toString());
            if(weixinOAuth2AccessToken==null || StringUtils.isBlank(weixinOAuth2AccessToken.getOpenId())){
                logger.error("因为weixinOAuth2AccessToken.getOpenId()==null,从session中获取");
                weixinOAuth2AccessToken = (WeixinOAuth2AccessToken) request.getSession().getAttribute("indexAccessToken");
                weiXinUser = CommonUtils.getWeiXinUser(weixinOAuth2AccessToken.getAccessToken(), weixinOAuth2AccessToken.getOpenId());
            }else{
                //将token放到session中
                request.getSession().setAttribute("indexAccessToken",weixinOAuth2AccessToken);
                weiXinUser = CommonUtils.getWeiXinUser(weixinOAuth2AccessToken.getAccessToken(), weixinOAuth2AccessToken.getOpenId());
            }
            if (weiXinUser != null) {
                openId = weiXinUser.getOpenId();
                logger.error("=weiXinUser不为null时获取的openId -- weiXinUser.getOpenId()====="+openId);
            }else{
                result.put("errorMsg", "系统繁忙");
                result.put("status", 400);
                this.print(response, result.toJSONString());
                return null;
            }
        }
        if (openId != null) {
            user = tsPlatformUserService.queryByOpenId(openId);
        }

        //如果根据openId获取不到用户信息 说明该用户是第一次访问微信公众号首页链接信息 保存用户信息到平台用户表
        if(null == user){
            user = createTsPlatformUser(weiXinUser);
            int i = tsPlatformUserService.insert(user);
            if (i <= 0) {
                result.put("errorMsg", "系统繁忙");
                result.put("status", 400);
                this.print(response, result.toJSONString());
                return null;
            }
        }
        logger.error("====user====="+user == null ? null : JSONObject.toJSONString(user));
        model.addAttribute("COOKIE_UID",user.getId());
        model.addAttribute("user",user);
        /*if(null!=user && StringUtils.isNotBlank(user.getMobile())){  //说明绑定过手机号 并且是平台用户
            if(ObjectUtils.equals(htmlFlag, ApiConstants.HTML_FLAG_0)){ //跳转入驻推影页面
                return "page/apply-info";
            }else if(ObjectUtils.equals(htmlFlag,ApiConstants.HTML_FLAG_1)){ //跳转我的奖励
                return "page/my-reward";
            }else if(ObjectUtils.equals(htmlFlag,ApiConstants.HTML_FLAG_2)){//跳转有奖邀请
                *//*if(!invitationController.check()){
                    return "page/pause-activity"; //跳转暂停页面
                }*//*
                return "index";
            }
        }else{
            //跳转绑定手机号页面
            model.addAttribute("htmlFlag",htmlFlag);
            return "page/login";
        }*/
        return "test1";
    }

    /**
     * 封装对象
     * @param weiXinUser
     * @return
     */
    private TsPlatformUser createTsPlatformUser(WeiXinUser weiXinUser) {
        TsPlatformUser tsPlatformUser = new TsPlatformUser();
        tsPlatformUser.setHead(weiXinUser.getHeadImgUrl());//头像
        tsPlatformUser.setCreateTime(new Date());//创建时间
        tsPlatformUser.setOpenId(weiXinUser.getOpenId());//openId 用户唯一标识
        tsPlatformUser.setNick(weiXinUser.getNickname());//用户昵称
        tsPlatformUser.setSource((byte) 1);//来源 微信公众号
        return tsPlatformUser;
    }


    /**
     * 输出信息到页面
     * @param response
     * @param content
     */
    private void print(HttpServletResponse response, String content) {
        PrintWriter writer = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            response.setHeader("Cache-Control", "no-cache");
            writer = response.getWriter();
            writer.print(content);
            writer.flush();
        } catch (Exception e) {
            logger.error("print error", e);
        } finally {
            try {
                if (null != writer) {
                    writer.close();
                }
            } catch (Exception e2) {
            }
        }
    }


}
